# -*- coding:utf-8 -*-

'''
仿照labelme的json文件写入自己的数据
'''
import cv2
import json
import os
import argparse

# 参考labelme的json格式重新生成json文件，
# 便可以使用labelme的接口解析数据

def dict_json(imageData,shapes,imagePath,fillColor=None,lineColor=None):
    '''

    :param imageData: str
    :param shapes: list
    :param imagePath: str
    :param fillColor: list
    :param lineColor: list
    :return: dict
    '''
    return {"imageData":imageData,"shapes":shapes,"fillColor":fillColor,
            'imagePath':imagePath,'lineColor':lineColor}

def dict_shapes(points,label,fill_color=None,line_color=None,area=0):
    return {'points':points,'fill_color':fill_color,'label':label,'line_color':line_color, 'area': area}

def make_json(json_path, page_config=None):
    if page_config is not None:
        config = page_config
    else:
        import config
    imageData="image data"
    areaNum = len(config.warp_regionList)
    shapes=[]
    for i in range(areaNum):
        label = config.warp_regionList[i]['attr']
        pointsNum = len(config.warp_regionList[i]['segmentation'])
        allPoints = config.warp_regionList[i]['segmentation']
        if label == 'imagegraph':
            label ='image'
        if label == 'tableimg':
            label = 'table'
        points = []
        for j in range(int(pointsNum/2)):
            temp = [float(allPoints[j*2]), float(allPoints[j*2 + 1])]
            points.append(temp)
        area = int(config.warp_regionList[i]['area'])
        #print(label)
        shapes.append(dict_shapes(points,label, None, None,area))
    lineColor = [0,255,0,128]
    fillColor = [255,0,0,128]
    imagePath = config.normal_imageName['jpgPath']
    imageName = os.path.split(os.path.splitext(imagePath)[0])[1]
    
    print(os.path.split(imagePath)[1] + "-->Start make json file!")
    data=dict_json(imageData,shapes,imagePath,fillColor,lineColor)
    # 写入json文件
    json_file = json_path + imageName +'.json'
    print(json_file)
    json.dump(data,open(json_file,'w'))

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Make json!!!")
    parser.add_argument("--jsonPath", default="./synthetic_data/json/", type=str, help="json path")
    opt = parser.parse_args()
    json_path = opt.jsonPath

    if not os.path.exists(json_path):
        os.mkdir(json_path)

    make_json(json_path)

    